Skip to content

Conversation

@Saahi30
Copy link
Collaborator

@Saahi30 Saahi30 commented Nov 2, 2025

Closes #

📝 Description

This pull request sets up a secure, modular, and production-ready Supabase integration for both the frontend (Next.js) and backend (FastAPI) projects. It updates environment variable handling, and improves project hygiene. The PR also adds health check endpoints, updates documentation, and ensures all configuration is managed via .env.example files.

🔧 Changes Made

  • Integrated Supabase JS client in the frontend with proper env variable usage.
  • Added Supabase Python client setup in the backend using the anon key.
  • Updated backend config to match .env.example and removed service key usage.
  • Added health check endpoints for backend and Supabase connectivity.
  • Improved .env.example files for both projects.
  • Added backend README with setup and usage instructions.
  • Updated documentation and project structure for clarity and security.

✅ Checklist

  • I have read the contributing guidelines.
  • I have added tests that prove my fix is effective or that my feature works.
  • I have added necessary documentation (if applicable).
  • Any dependent changes have been merged and published in downstream modules.

Summary by CodeRabbit

  • New Features

    • Supabase integration added for backend and frontend (runtime client + health checks)
  • Documentation

    • New Supabase setup guide with quick start, env, health check, and next steps
    • README wording and formatting improvements
  • Configuration

    • New Supabase environment variables and expanded server/CORS settings
    • Dependency list updated to include Supabase client support

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 2, 2025

Walkthrough

Adds Supabase integration across frontend and backend: new docs, env updates, Supabase clients (frontend/backend), config fields, a health check router and startup validation that verifies Supabase connectivity, and TypeScript types for database schema.

Changes

Cohort / File(s) Summary
Documentation
README.md, SUPABASE_SETUP.md
Minor README formatting/wording edits; new SUPABASE_SETUP.md with step-by-step Supabase integration guidance for frontend (Next.js) and backend (FastAPI).
Backend Configuration & Dependencies
backend/app/core/config.py, backend/env_example, backend/requirements.txt
New Supabase config fields (supabase_url, supabase_key), made database_url/ai_api_key optional, added groq_api_key, CORS/server settings, updated env example entries, and added supabase>=2.0.0 to requirements.
Backend Services
backend/app/services/__init__.py, backend/app/services/supabase_client.py
Added services package and module-level Supabase client (supabase) initialized from settings.
Backend Health & Startup
backend/app/api/routes/health.py, backend/app/main.py
New health routes (GET /health, GET /health/supabase) and startup validation in main.py that runs a lightweight Supabase query and registers the health router.
Frontend Config & Tooling
frontend/.env.example, frontend/tsconfig.json
Ensured trailing newline in .env.example; adjusted tsconfig.json (jsx to react-jsx, formatted arrays) with no behavioral regressions.
Frontend Supabase Integration & Types
frontend/lib/supabaseClient.ts, frontend/types/supabase.ts
New exported singleton Supabase client with env validation; new Json type and Database interface scaffold for strongly-typed Supabase interactions.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application Startup
    participant Main as backend/app/main.py
    participant ClientSvc as backend.app.services.supabase_client
    participant DB as Supabase DB

    App->>Main: start()
    Main->>ClientSvc: import supabase (module init)
    Main->>ClientSvc: perform test query
    ClientSvc->>DB: select * from test_table limit 1
    alt Query Success
        DB-->>ClientSvc: row
        ClientSvc-->>Main: connected
        Main-->>App: startup complete
    else Table Missing
        DB-->>ClientSvc: error (table not found)
        ClientSvc-->>Main: client init, table missing (warning)
        Main-->>App: startup complete (with warning)
    else Connection Failure
        DB-->>ClientSvc: connection error
        ClientSvc-->>Main: error
        Main-->>App: startup failed
    end
Loading
sequenceDiagram
    participant Client as HTTP Client
    participant API as backend/app/api/routes/health.py
    participant ClientSvc as backend.app.services.supabase_client
    participant DB as Supabase DB

    Client->>API: GET /health
    API-->>Client: {"status":"healthy","message":"Backend is running"}

    Client->>API: GET /health/supabase
    API->>ClientSvc: run health query
    ClientSvc->>DB: select * from test_table limit 1
    alt Success
        DB-->>ClientSvc: row
        ClientSvc-->>API: {"connected": true, "message": "..."}
        API-->>Client: 200 OK
    else Error (table missing)
        DB-->>ClientSvc: error
        ClientSvc-->>API: {"connected": true, "error": "..."}
        API-->>Client: 200 OK (with note)
    else Connection Failure
        DB-->>ClientSvc: connection error
        ClientSvc-->>API: {"connected": false, "error": "..."}
        API-->>Client: 503 Service Unavailable
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

  • Attention areas:
    • backend/app/main.py — startup validation ordering and failure handling
    • backend/app/api/routes/health.py — error handling and response shapes for Supabase checks
    • backend/app/core/config.py — new optional fields and defaults, ensure env parsing matches expectations
    • frontend/lib/supabaseClient.ts — runtime behavior when env vars are missing

Possibly related PRs

Suggested labels

documentation

Suggested reviewers

  • ishaanxgupta

Poem

🐰 I hopped through configs, keys in paw,
Supabase whispers, ready to draw.
Health checks hum and clients align,
Frontend, backend — everything fine.
A tiny rabbit dances — integration divine! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "Supabase setup" directly corresponds to the primary objective of the changeset, which implements comprehensive Supabase integration for both frontend and backend systems. The title accurately summarizes the main change—introducing Supabase client initialization, configuration, health checks, and documentation across multiple application layers. The title is concise and clear enough that a developer scanning the commit history would immediately understand this PR establishes Supabase connectivity. While "setup" is somewhat generic as a term, combined with "Supabase" it effectively communicates the scope and intent of the changes.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch supabase_setup

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Saahi30
Copy link
Collaborator Author

Saahi30 commented Nov 2, 2025

@CodeRabbit review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 2, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
frontend/.env.example (1)

1-6: LGTM!

The addition of a trailing newline follows best practices for text files.

For improved organization, consider alphabetically ordering the environment variables (e.g., move NEXT_PUBLIC_APP_URL before NEXT_PUBLIC_SUPABASE_ANON_KEY), though this is purely a style preference.

README.md (1)

94-180: Documentation updates look good.

The formatting improvements and updated instructions align well with the Supabase integration.

Static analysis suggests adding a language specifier to the fenced code block at line 103. Consider specifying the language (e.g., sh or bash) for better syntax highlighting and documentation clarity.

frontend/lib/supabaseClient.ts (1)

3-10: Refactor non-null assertions for better type safety.

Lines 3-4 use the non-null assertion operator (!) which tells TypeScript these values are definitely defined, but then lines 6-10 perform a runtime check for missing values. This is contradictory and reduces TypeScript's ability to help prevent errors.

Apply this diff to remove the non-null assertions and handle undefined values properly:

-const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
-const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
+const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
+const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
 
 if (!supabaseUrl || !supabaseAnonKey) {
   throw new Error(
     "Missing Supabase environment variables. Please check your .env file."
   );
 }
 
 export const supabase = createClient(supabaseUrl, supabaseAnonKey);

This way, TypeScript will properly recognize that the values are verified before use in createClient.

backend/app/main.py (1)

9-20: Move the Supabase validation into a proper FastAPI startup hook.
The current block executes whenever this module is imported (tests, CLI utilities, ASGI reloads), making a real Supabase call before the app is even running—which is brittle and can block or fail in non-server contexts. FastAPI already exposes a startup event; please migrate the probe there.

-# Verify Supabase client initialization on startup
-try:
-    # Try a lightweight query
-    response = supabase.table("_supabase_test").select("*").limit(1).execute()
-    print("✅ Supabase client initialized successfully.")
-except Exception as e:
-    error_msg = str(e)
-    if "Could not find the table" in error_msg:
-        print("⚠️ Supabase client connected, but test table does not exist. Connection is working.")
-    else:
-        print(f"❌ Failed to verify Supabase connection: {e}")
+@app.on_event("startup")
+def verify_supabase_connection() -> None:
+    try:
+        supabase.table("_supabase_test").select("*").limit(1).execute()
+        print("✅ Supabase client initialized successfully.")
+    except Exception as e:
+        error_msg = str(e)
+        if "Could not find the table" in error_msg:
+            print("⚠️ Supabase client connected, but test table does not exist. Connection is working.")
+        else:
+            print(f"❌ Failed to verify Supabase connection: {e}")
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab923da and ccadd11.

📒 Files selected for processing (13)
  • README.md (3 hunks)
  • SUPABASE_SETUP.md (1 hunks)
  • backend/app/api/routes/health.py (1 hunks)
  • backend/app/core/config.py (1 hunks)
  • backend/app/main.py (2 hunks)
  • backend/app/services/__init__.py (1 hunks)
  • backend/app/services/supabase_client.py (1 hunks)
  • backend/env_example (1 hunks)
  • backend/requirements.txt (1 hunks)
  • frontend/.env.example (1 hunks)
  • frontend/lib/supabaseClient.ts (1 hunks)
  • frontend/tsconfig.json (3 hunks)
  • frontend/types/supabase.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-05-07T21:28:06.358Z
Learnt from: muntaxir4
Repo: AOSSIE-Org/InPactAI PR: 56
File: Backend/app/services/redis_client.py:1-4
Timestamp: 2025-05-07T21:28:06.358Z
Learning: Hardcoded Redis connection parameters in Backend/app/services/redis_client.py are intentional during development, with plans to implement environment variable configuration later during production preparation.

Applied to files:

  • backend/env_example
🪛 dotenv-linter (4.0.0)
frontend/.env.example

[warning] 5-5: [UnorderedKey] The NEXT_PUBLIC_APP_URL key should go before the NEXT_PUBLIC_SUPABASE_ANON_KEY key

(UnorderedKey)

🪛 markdownlint-cli2 (0.18.1)
SUPABASE_SETUP.md

92-92: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


103-103: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

README.md

103-103: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🪛 Ruff (0.14.2)
backend/app/main.py

14-14: Do not catch blind exception: Exception

(BLE001)

backend/app/core/config.py

21-21: Possible binding to all interfaces

(S104)

backend/app/api/routes/health.py

24-24: Local variable response is assigned to but never used

Remove assignment to unused variable response

(F841)


26-30: Consider moving this statement to an else block

(TRY300)


31-31: Do not catch blind exception: Exception

(BLE001)

🔇 Additional comments (6)
backend/app/services/__init__.py (1)

1-3: LGTM!

Clean module initialization with an appropriate docstring.

frontend/tsconfig.json (1)

4-8: LGTM!

The configuration updates are appropriate:

  • Switching to "react-jsx" enables the modern JSX transform (React 17+)
  • Multi-line array formatting improves readability

Also applies to: 18-18, 26-28, 39-41

backend/env_example (1)

3-23: LGTM!

The environment variable structure is well-organized with clear sections and helpful comments. The configuration appropriately supports the Supabase integration with both required and optional settings clearly marked.

backend/requirements.txt (1)

21-21: LGTM!

The Supabase dependency is correctly added with an appropriate minimum version constraint.

frontend/lib/supabaseClient.ts (1)

12-12: LGTM!

The singleton pattern for the Supabase client export is appropriate for frontend usage.

backend/app/services/supabase_client.py (1)

1-3: LGTM!

The imports are appropriate for creating a Supabase client with configuration from settings.

@Saahi30
Copy link
Collaborator Author

Saahi30 commented Nov 2, 2025

@CodeRabbit review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 2, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@Saahi30
Copy link
Collaborator Author

Saahi30 commented Nov 2, 2025

@CodeRabbit review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 2, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
SUPABASE_SETUP.md (2)

93-100: Add language identifier to fenced code block.

The directory tree structure should specify a language identifier (e.g., plaintext or text) for better rendering and linting compliance.

Apply this diff:

-```
+```plaintext
 frontend/
 ├── lib/
 │   └── supabaseClient.ts    # Supabase client initialization

104-115: Add language identifier to fenced code block.

The directory tree structure should specify a language identifier (e.g., plaintext or text) for better rendering and linting compliance.

Apply this diff:

-```
+```plaintext
 backend/
 ├── app/
 │   ├── core/
backend/app/api/routes/health.py (2)

23-23: Remove unused variable.

The response variable is assigned but never used. Either remove it or use it for additional validation/debugging.

Apply this diff if you don't need the response:

-        response = supabase.table("_supabase_test").select("*").limit(1).execute()
+        supabase.table("_supabase_test").select("*").limit(1).execute()

33-38: Clarify operator precedence.

Line 35 mixes and with or without parentheses, making precedence unclear. Add parentheses to the and subexpression for better readability.

Apply this diff:

     if (
         "does not exist" in error_msg or
-        "relation" in error_msg and "does not exist" in error_msg or
+        ("relation" in error_msg and "does not exist" in error_msg) or
         "Could not find the table" in error_msg or
         "PGRST205" in error_msg
     ):
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ccadd11 and 582df75.

📒 Files selected for processing (3)
  • SUPABASE_SETUP.md (1 hunks)
  • backend/app/api/routes/health.py (1 hunks)
  • backend/app/services/supabase_client.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/app/services/supabase_client.py
🧰 Additional context used
🪛 markdownlint-cli2 (0.18.1)
SUPABASE_SETUP.md

93-93: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


104-104: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🪛 Ruff (0.14.2)
backend/app/api/routes/health.py

23-23: Local variable response is assigned to but never used

Remove assignment to unused variable response

(F841)


25-29: Consider moving this statement to an else block

(TRY300)


30-30: Do not catch blind exception: Exception

(BLE001)


35-35: Parenthesize a and b expressions when chaining and and or together, to make the precedence clear

Parenthesize the and subexpression

(RUF021)

🔇 Additional comments (4)
SUPABASE_SETUP.md (2)

52-56: Security guidance now correctly aligned with backend configuration.

The documentation now properly instructs users to use SUPABASE_KEY (anon key) and explicitly warns against storing the service role key. This matches the backend configuration expectations and resolves the previously flagged issue.


132-138: Security notes are comprehensive and accurate.

The security guidelines correctly emphasize using anon keys and avoiding service role keys in backend environment files, which aligns well with the principle of least privilege.

backend/app/api/routes/health.py (2)

8-11: LGTM!

The basic health check endpoint is straightforward and correctly implemented.


13-51: Exception handling now properly distinguishes failure types.

The updated logic correctly identifies table-not-found scenarios (returns connected=True, status="ready") and treats all other errors as genuine failures (returns connected=False, status="unhealthy"). This resolves the previously flagged issue and will properly alert monitoring systems to real connectivity problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants